package by.gravity.pvh;

import java.util.concurrent.TimeUnit;

import org.holoeverywhere.app.Activity;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import by.gravity.pvh.adapter.PVHFragmentPagerAdapter;
import by.gravity.pvh.data.PreferenceDataManager;
import by.gravity.pvh.data.RateDataManager;
import by.gravity.pvh.data.RateDataManager.onLoadCompleteListener;
import by.gravity.pvh.fragments.BalconyBlockFragment;
import by.gravity.pvh.fragments.BalconyRamaFragment;
import by.gravity.pvh.fragments.CommonFragment;
import by.gravity.pvh.fragments.DoorFragment;
import by.gravity.pvh.fragments.WindowFragment;

import com.viewpagerindicator.TabPageIndicator;

public class MainActivity extends Activity {

	private PVHFragmentPagerAdapter adapter;
	private ViewPager pager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_main);

		pager = (ViewPager) findViewById(R.id.pager);

		adapter = new PVHFragmentPagerAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.titles));
		adapter.addFragment(new WindowFragment());
		adapter.addFragment(new DoorFragment());
		adapter.addFragment(new BalconyBlockFragment());
		adapter.addFragment(new BalconyRamaFragment());
		pager.setAdapter(adapter);
		pager.setOffscreenPageLimit(4);

		TabPageIndicator titleIndicator = (TabPageIndicator) findViewById(R.id.indicator);
		titleIndicator.setViewPager(pager);

		if (TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis() - PreferenceDataManager.getLastUpdateTime(this)) >= 12) {
			loadRates();
		}

	}

	private void loadRates() {
		RateDataManager.getInstance().getRate(this, new onLoadCompleteListener() {

			@Override
			public void onLoadComplete(String result) {
				PreferenceDataManager.saveLastUpdateTime(MainActivity.this);
				PreferenceDataManager.saveRate(MainActivity.this, result);
				for (int i = 0; i < adapter.getCount(); i++) {
					((CommonFragment) adapter.getItem(i)).updateRate(result);
				}
			}
		});
	}

	public WindowFragment getWindowFragment() {
		pager.setCurrentItem(0);
		return (WindowFragment) adapter.getItem(0);
	}

	public DoorFragment getDoorFragment() {
		pager.setCurrentItem(1);
		return (DoorFragment) adapter.getItem(1);
	}

	public BalconyBlockFragment getBalconyBlockFragment() {
		pager.setCurrentItem(2);
		return (BalconyBlockFragment) adapter.getItem(2);
	}

	public BalconyRamaFragment getBalconyRamaFragment() {
		pager.setCurrentItem(3);
		return (BalconyRamaFragment) adapter.getItem(3);
	}

}
